package com.ease.concurrent.thread.communication;

/**
 * 两个线程交替打印
 *
 * notify()方法唤醒对象后，如果拿不到锁，应该处于blocked阻塞状态
 *
 * @author: chenhs
 * @date: Created in 15:57 2019/12/30
 **/
public class Demo1_WaitNotify {

    static int i = 0;
    static Object obj = new Object();
    static int limit = 10;

    public static void main(String[] args) {

        new Thread(() -> {
            synchronized (obj) {

                while (i < limit) {
                    System.out.println("t1: " + (++i));
                    /** 从obj锁的等待队列中唤醒一个对象（t2）, t2.state = BLOCKED */
                    obj.notify();

                    try {
                        /**
                         * t1释放锁，进入obj锁的等待队列, t1.state = WAITING,
                         * t2拿到锁，t2.state = RUNNABLE
                         */
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                /** 这个很重要, 线程结束时将t1（自己）唤醒 */
                obj.notify();
            }
        }).start();


        new Thread(() -> {
            synchronized (obj) {

                while (i < limit) {
                    System.out.println("    t2: " + (++i));
                    /** 唤醒obj锁等待队列中一个对象（t1）, t1.state = BLOCKED */
                    obj.notify();

                    try {
                        /**
                         * t2释放锁，进入obj锁的等待队列, t2.state = WAITING,
                         * t1拿到锁，t1.state = RUNNABLE
                         */
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                /** 这个很重要, 线程结束时将t2（自己）唤醒 */
                obj.notify();
            }
        }).start();


    }

}
